using DemoWebapi01.Entities;
using DemoWebapi01.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DemoWebapi01.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class QuestionController : ControllerBase
    {
        private readonly MyDbContext _context;

        public QuestionController(MyDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 获取所有问题
        /// </summary>
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Question>>> GetQuestions()
        {
            return await _context.Questions
                .Include(q => q.Category)
                .ToListAsync();
        }
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Question>>> GetQuestionsByConditions(Guid? categoryId, string difficulty, string questionType)
        {
            var tempRes = _context.Questions.Where(x => !x.IsDeleted);
            if (categoryId != null && categoryId != Guid.Empty)
            {
                var category = await _context.Categories.FindAsync(categoryId);
                if (category == null)
                {
                    return NotFound("分类不存在");
                }
                tempRes = tempRes.Include(q => q.Category).Where(q => q.CategoryId == categoryId);
            }
            if (!string.IsNullOrWhiteSpace(difficulty))
            {
                if (!new[] { QuestionDifficulty.Easy, QuestionDifficulty.Medium, QuestionDifficulty.Hard }.Contains(difficulty))
                {
                    return BadRequest("无效的难度值，有效值为: easy, medium, hard");
                }
                tempRes = tempRes.Where(q => q.Difficulty == difficulty);
            }
            if (!string.IsNullOrWhiteSpace(questionType))
            {
                if (!new[] { QuestionType.SingleChoice, QuestionType.MultipleChoice, QuestionType.TrueFalse, QuestionType.FillBlank, QuestionType.ShortAnswer }.Contains(questionType))
                {
                    return BadRequest("无效的问题类型");
                }
                tempRes = tempRes.Where(q => q.QuestionType == questionType);
            }

            return await tempRes.ToListAsync();
        }
        /// <summary>
        /// 按分类获取问题
        /// </summary>
        [HttpGet("category/{categoryId}")]
        public async Task<ActionResult<IEnumerable<Question>>> GetQuestionsByCategory(Guid categoryId)
        {
            var category = await _context.Categories.FindAsync(categoryId);
            if (category == null)
            {
                return NotFound("分类不存在");
            }

            return await _context.Questions
                .Include(q => q.Category)
                .Where(q => q.CategoryId == categoryId)
                .ToListAsync();
        }
        /// <summary>
        /// 获取单个问题
        /// </summary>
        [HttpGet("{id}")]
        public async Task<ActionResult<Question>> GetQuestion(Guid id)
        {
            var question = await _context.Questions
                .Include(q => q.Category)
                .FirstOrDefaultAsync(q => q.Id == id);

            if (question == null)
            {
                return NotFound("问题不存在");
            }

            return question;
        }

        /// <summary>
        /// 创建新问题
        /// </summary>
        [HttpPost]
        public async Task<ActionResult<Question>> CreateQuestion(QuestionCreateRequest request)
        {
            // 参数验证
            if (string.IsNullOrEmpty(request.Content))
            {
                return BadRequest("问题内容不能为空");
            }

            // 检查分类是否存在
            var category = await _context.Categories.FindAsync(request.CategoryId);
            if (category == null)
            {
                return BadRequest("指定的分类不存在");
            }

            // 验证问题类型
            if (!new[] {
                QuestionType.SingleChoice,
                QuestionType.MultipleChoice,
                QuestionType.TrueFalse,
                QuestionType.FillBlank,
                QuestionType.ShortAnswer
            }.Contains(request.QuestionType))
            {
                return BadRequest("无效的问题类型");
            }

            // 验证难度
            if (!new[] { QuestionDifficulty.Easy, QuestionDifficulty.Medium, QuestionDifficulty.Hard }.Contains(request.Difficulty))
            {
                return BadRequest("无效的难度值，有效值为: easy, medium, hard");
            }

            // 创建新问题
            var question = new Question
            {
                Content = request.Content,
                QuestionType = request.QuestionType,
                Difficulty = request.Difficulty,
                Explanation = request.Explanation,
                Status = "active",
                CategoryId = request.CategoryId,
                CreatedOn = DateTime.Now
            };

            _context.Questions.Add(question);
            await _context.SaveChangesAsync();

            // 创建选项
            foreach (var option in request.Options)
            {
                var questionOption = new QuestionOption
                {
                    Content = option.Content,
                    ContentCN = option.ContentCN,
                    IsCorrect = option.IsCorrect,
                    QuestionId = question.Id // 关联到新创建的问题
                };
                _context.QuestionOptions.Add(questionOption);
            }
            await _context.SaveChangesAsync();

            // 重新获取问题，包括分类和选项信息
            var createdQuestion = await _context.Questions
                .Include(q => q.Category)
                .Include(q => q.QuestionOptions)
                .FirstOrDefaultAsync(q => q.Id == question.Id);

            return CreatedAtAction(nameof(GetQuestion), new { id = question.Id }, createdQuestion);
        }

        /// <summary>
        /// 更新问题
        /// </summary>
        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateQuestion(Guid id, QuestionUpdateRequest request)
        {
            var question = await _context.Questions
                .Include(q => q.QuestionOptions) // 包含选项
                .FirstOrDefaultAsync(q => q.Id == id);
            if (question == null)
            {
                return NotFound("问题不存在");
            }

            // 更新问题信息
            if (!string.IsNullOrEmpty(request.Content))
                question.Content = request.Content;

            if (!string.IsNullOrEmpty(request.QuestionType))
            {
                if (!new[] {
                    QuestionType.SingleChoice,
                    QuestionType.MultipleChoice,
                    QuestionType.TrueFalse,
                    QuestionType.FillBlank,
                    QuestionType.ShortAnswer
                }.Contains(request.QuestionType))
                {
                    return BadRequest("无效的问题类型");
                }
                question.QuestionType = request.QuestionType;
            }

            if (!string.IsNullOrEmpty(request.Difficulty))
            {
                if (!new[] { QuestionDifficulty.Easy, QuestionDifficulty.Medium, QuestionDifficulty.Hard }.Contains(request.Difficulty))
                {
                    return BadRequest("无效的难度值，有效值为: easy, medium, hard");
                }
                question.Difficulty = request.Difficulty;
            }

            if (request.Explanation != null)
                question.Explanation = request.Explanation;

            question.ModifiedOn = DateTime.Now;

            // 更新选项
            // 清除现有选项
            _context.QuestionOptions.RemoveRange(question.QuestionOptions);

            // 添加新选项
            foreach (var option in request.Options)
            {
                var questionOption = new QuestionOption
                {
                    Content = option.Content,
                    ContentCN = option.ContentCN,
                    IsCorrect = option.IsCorrect,
                    QuestionId = question.Id // 关联到更新的问题
                };
                _context.QuestionOptions.Add(questionOption);
            }

            _context.Entry(question).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!QuestionExists(id))
                {
                    return NotFound("问题不存在");
                }
                else
                {
                    throw;
                }
            }

            // 重新获取更新后的问题，包括分类和选项信息
            var updatedQuestion = await _context.Questions
                .Include(q => q.Category)
                .Include(q => q.QuestionOptions)
                .FirstOrDefaultAsync(q => q.Id == id);

            return Ok(updatedQuestion);
        }

        /// <summary>
        /// 删除问题
        /// </summary>
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteQuestion(Guid id, [FromQuery] string operatorName)
        {
            var question = await _context.Questions.FindAsync(id);
            if (question == null)
            {
                return NotFound("问题不存在");
            }

            // 执行软删除
            question.IsDeleted = true;
            question.DeletedOn = DateTime.Now;
            question.DeletedBy = operatorName;

            _context.Entry(question).State = EntityState.Modified;
            await _context.SaveChangesAsync();

            return Ok("问题删除成功");
        }

        private bool QuestionExists(Guid id)
        {
            return _context.Questions.Any(e => e.Id == id);
        }
    }
}